// userStore
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { Api } from '@/apis/index'
import { useRouter } from 'vue-router'

export const useUserStore = defineStore('user', () => {
    const user = ref(null)
    const token = ref()
    const router = useRouter()

    const getUserInf = async () => {
        const ans = await Api.getUserInf()
        if (ans.code === 200) {
            user.value = ans.data
        } else {
            console.log(ans.msg)
        }
    }

    const login = async (form) => {
        const res = await Api.login(form)
        if (res.code === 200) {
            token.value = res.data.token
            user.value = res.data.user
            localStorage.setItem('token', res.data)
            router.push('/')
        }
    }

    return {
        user,
        getUserInf,
        token,
        login
    }
}, {
    persist: true,
})